package com.ybzl.common.core.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 *
 * @author dtf
 * <p>
 * 注意额外开销（使用string类型处理对象类型数据时,  "@class": "com.ybzl.common.core.domain.entity.SysRole",）
 * {
 * "@class": "com.ybzl.common.core.domain.entity.SysRole",
 * "createBy": null,
 * "createTime": null,
 * "updateBy": null,
 * "updateTime": null,
 * "remark": null,
 * "roleId": 1,
 * "roleName": "超级管理员",
 * "roleKey": "admin",
 * "roleSort": 1,
 * "dataScope": "1",
 * "menuCheckStrictly": false,
 * "deptCheckStrictly": false,
 * "status": "0",
 * "delFlag": null,
 * "flag": false,
 * "menuIds": null,
 * "deptIds": null,
 * "permissions": null,
 * "admin": true
 * }
 */

/**
 * redisTemplate.opsForValue() ValueOperations 操作String类型数据
 * redisTemplate.opsForHash()  HashOperations  操作Hash类型数据
 * redisTemplate.opsForList()  ListOperations  操作List类型数据
 * redisTemplate.opsForSet()   SetOperations   操作Set类型数据
 * redisTemplate.opsForZSet()  ZSetOperations  操作SortedSet类型数据
 *
 * https://blog.51cto.com/u_16099347/9881800
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        // 配置redisTemplate
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 解决jackson2无法反序列化LocalDateTime的问题(暂时未解决)
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知属性
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);


        // String 类型操作时： key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // String 类型操作时： value序列化，在字符串操作下使用该序列化器直接存储对象的时候会产生 类的全限定名描述
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        // Hash 类型操作时：  key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash 类型操作时：  value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public DefaultRedisScript<Long> limitScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    /**
     * 限流脚本
     */
    private String limitScriptText() {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }
}
